package top.wilsonlv.jaguar.security.component;

import org.springframework.http.MediaType;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import top.wilsonlv.jaguar.commons.web.response.JsonResult;
import top.wilsonlv.jaguar.commons.web.response.ResultCode;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lvws
 * @since 2022/3/14 0014
 */
public class JaguarSessionExpiredStrategy implements SessionInformationExpiredStrategy {

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        HttpServletResponse response = event.getResponse();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        JsonResult<Object> jsonResult = new JsonResult<>(ResultCode.UNAUTHORIZED, null, "会话过期");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(jsonResult.toJsonStr());
        }
    }
}
